let skip_defaults_vim=1         "设置跳过加载默认vim配置
set modelines=0		" CVE-2007-2438 禁用模式行（安全措施）

" Don't write backup file if vim is being called by "crontab -e"
au BufWrite /private/tmp/crontab.* set nowritebackup nobackup
" Don't write backup file if vim is being called by "chpass"
au BufWrite /private/etc/pw.* set nowritebackup nobackup

"自动补全标签
inoremap ><Tab> ><Esc>F<lyt>o</<C-r>"><Esc>O

"==============================================================================
" vim 内置配置
"==============================================================================

" 设置 vimrc 修改保存后立刻生效，不用在重新打开
" 建议配置完成后将这个关闭
autocmd BufWritePost $MYVIMRC source $MYVIMRC

set nocompatible	"关闭兼容模式，去掉有关vi一致性模式
set backspace=2		" more powerful backspacing
"set listchars=eol:$,tab:>-,space:_ "设置显示tab和空格
""set list

syntax enable	"语法高亮
syntax on       "开启文件类型侦测
set incsearch  " 开启实时搜索
set ignorecase   " 搜索时大小写不敏感
filetype plugin indent on    " 启用自动补全

"--autocompletion
filetype plugin on
set omnifunc=syntaxcomplete#Complete

au InsertLeave *.py,*.sh,*.php write   " 退出插入模式指定类型的文件自动保存

set nu " 设置行号
set cursorline "突出显示当前行
set cursorcolumn " 突出显示当前列
"set showmatch " 显示括号匹配，注释掉也可以，可能有插件开启了

" 缩进
set tabstop=4    "Tab键的宽度四个空格
set softtabstop=4   "软制表符宽度为四个空格,表示在编辑模式的时候按退格键的时候退回缩进的长度
set shiftwidth=4    "把每级缩进设置为四个空格
set expandtab   "缩进用空格来表示,noexpandtab 则是用制表符表示一个缩进
"set ai       "set autoindent 打开缩进，继承前一行的缩进方式，适用于多行注释

set hlsearch
set encoding=utf-8
set fileencodings=utf-8,ucs-bom,GB2312,big5

" 调节调节
nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>
" 调节窗框
nmap wj :resize -3<CR>
nmap wk :resize +3<CR>
nmap wh :vertical resize -3<CR>
nmap wl :vertical resize +3<CR>


"python特殊配置
let python_highlight_all=1
au Filetype python set tabstop=4
au Filetype python set softtabstop=4
au Filetype python set shiftwidth=4
au Filetype python set textwidth=100
au Filetype python set expandtab
au Filetype python set autoindent
au Filetype python set fileformat=unix
autocmd Filetype python set foldmethod=indent
autocmd Filetype python set foldlevel=99

"前台开发配置
au BufNewFile,BufRead *.html,*.js,*.vue set tabstop=2
au BufNewFile,BufRead *.html,*.js,*.vue set softtabstop=2
au BufNewFile,BufRead *.html,*.js,*.vue set shiftwidth=2
au BufNewFile,BufRead *.html,*.js,*.vue set expandtab
au BufNewFile,BufRead *.html,*.js,*.vue set autoindent
au BufNewFile,BufRead *.html,*.js,*.vue set fileformat=unix
"这个是解决偶尔高亮失效的，貌似没什么鸟用
autocmd FileType vue syntax sync fromstart

"Start自动插入文件头-------------------------------------------------------------------------------
"新建.py,.h,.sh,.java文件，自动插入文件头 
autocmd BufNewFile *.py,*.sh,*.vue exec ":call SetTitle()" 
 
""定义函数SetTitle，自动插入文件头 
func SetTitle() 
    "如果文件类型为.sh文件 
    if expand("%:e")== 'sh' 
        call setline(1,"\#########################################################################") 
        call setline(line(".")+1, "\# File Name: ".expand("%")) 
        call setline(line(".")+2, "\# Author: bobo") 
        call setline(line(".")+3, "\# mail: gg-tc@163.com") 
        call setline(line(".")+4, "\# Created Time: ".strftime("%Y%m%d")) 
        call setline(line(".")+5, "\#########################################################################") 
        call setline(line(".")+6, "\#!/bin/bash") 
        call setline(line(".")+7, "") 
    elseif expand("%:e") == 'py' 
        call setline(1, "#!/usr/bin/env python3") 
        call setline(line(".")+1, "# -*- coding: utf-8 -*-")
        call setline(line(".")+2, "# File Name: ".expand("%"))
        call setline(line(".")+3, "# Author: bobo")
        call setline(line(".")+4, "# Created Time: ".strftime("%Y%m%d"))
        call setline(line(".")+5, "")
    elseif expand("%:e") == 'vue'
        call setline(1, "<template>") 
        call setline(line(".")+1, "  <div>")
        call setline(line(".")+2, "    ")
        call setline(line(".")+3, "  </div>")
        call setline(line(".")+4, "</template>")
        call setline(line(".")+5, "")
        call setline(line(".")+6, "<script setup lang='ts'>")
        call setline(line(".")+7, "  ")
        call setline(line(".")+8, "</script>")
        call setline(line(".")+9, "")
        call setline(line(".")+10, "<style>")
        call setline(line(".")+11, "  ")
        call setline(line(".")+12, "</style>")
    endif
    "新建文件后，自动定位到文件末尾
    autocmd BufNewFile * normal G
endfunc 
"End自动插入文件头-------------------------------------------------------------------------------


" 启动时自动开启项目文件树
autocmd VimEnter *.py,*.vue,*.js NERDTree


" 定义快捷键的前缀，即<Leader>，默认“\”
let mapleader=";"
nmap <Leader>w :w<CR>
nmap <Leader>qa :qa<CR>
inoremap jj <Esc>

" ==== 系统剪切板复制粘贴 ====
" v 模式下复制内容到系统剪切板
vmap <Leader>c "+yy
" n 模式下复制一行到系统剪切板
nmap <Leader>c "+yy
" n 模式下粘贴系统剪切板的内容
nmap <Leader>v "+p


" 插件开始的位置
call plug#begin('~/.vim/plugged')

" Shorthand notation; fetches https://github.com/junegunn/vim-easy-align
" 可以快速对齐的插件
Plug 'junegunn/vim-easy-align'
xmap ea <Plug>(EasyAlign)
nmap ea <Plug>(EasyAlign)


" 启动时显示最近打开文件列表
Plug 'mhinz/vim-startify'

" 快速搜索
Plug 'junegunn/fzf', {'do': { -> fzf#install() }}
Plug 'junegunn/fzf.vim'
nnoremap ff :Files<CR>
nnoremap fg :Ag<CR>
nnoremap fl :Lines<CR>
nnoremap fm :Marks<CR>
nnoremap fb :Buffers<CR>
"let g:fzf_layout = { 'window': '-tabnew' }


" 用来提供一个导航目录的侧边栏
Plug 'scrooloose/nerdtree'

" 可以使 nerdtree 的 tab 更加友好些
Plug 'jistr/vim-nerdtree-tabs'

" 可以在导航目录中看到 git 版本信息
Plug 'Xuyuanp/nerdtree-git-plugin'

" html, css编写插件
Plug 'mattn/emmet-vim'

" 查看当前代码文件中的变量和函数列表的插件，
" 可以切换和跳转到代码中对应的变量和函数的位置
" 大纲式导航, Go 需要 https://github.com/jstemmer/gotags 支持
Plug 'preservim/tagbar'

" 自动补全括号的插件，包括小括号，中括号，以及花括号
Plug 'jiangmiao/auto-pairs'

" Vim状态栏插件，包括显示行号，列号，文件类型，文件名，以及Git状态
Plug 'vim-airline/vim-airline'

" 代码自动完成，安装完插件还需要额外配置才可以使用
" Plug 'Valloric/YouCompleteMe'
" 不用上面的插件安装方法,不能科学上网失败概率太高，用下面方法替代
"sudo apt-get install vim-youcompleteme
"sudo vim-addon-manager install youcompleteme

" 可以在文档中显示 git 信息
"Plug 'airblade/vim-gitgutter'

" 下面两个插件要配合使用，可以自动生成代码块
Plug 'SirVer/ultisnips'
Plug 'honza/vim-snippets'

" 可以在 vim 中使用 tab 补全
"Plug 'vim-scripts/SuperTab'

" 可以在 vim 中自动完成
"Plug 'Shougo/neocomplete.vim'

"
Plug 'tpope/vim-surround'

" 配色方案
Plug 'KeitaNakamura/neodark.vim'
" colorscheme neodark
Plug 'crusoexia/vim-monokai'
" colorscheme monokai
Plug 'acarapetis/vim-colors-github'
" colorscheme github
Plug 'rakr/vim-one'
" colorscheme one
Plug 'morhetz/gruvbox'
" colorscheme gruvbox


" markdown 插件
"Plug 'iamcco/mathjax-support-for-mkdp'
"Plug 'iamcco/markdown-preview.vim'

"使Vim编辑文件内的括号，变为彩虹色
Plug 'kien/rainbow_parentheses.vim'
"使Vim支持JavaScript的语法高亮和代码格式化
Plug 'pangloss/vim-javascript'

"代码格式化工具
"Plug 'Chiel92/vim-autoformat'

"显示缩进线
Plug 'Yggdroot/indentLine'
"代码检测工具支持
Plug 'w0rp/ale'

"Vue支持
Plug 'posva/vim-vue'

"语法检查，配合 let g:syntastic_javascript_checkers = ['eslint']
Plug 'scrooloose/syntastic'

"注释和取消注释
Plug 'scrooloose/nerdcommenter'

" 插件结束的位置，插件全部放在此行上面
call plug#end()

"====================================================================
" indentLine插件
"====================================================================
let g:indentLine_setColors = 239
let g:indentLine_char_list = ['|', '¦', '┆', '┊']

"====================================================================
" emmet插件 快捷键<C-y>
"====================================================================
let g:user_emmet_expandabbr_key = '<Tab><Tab>'

"====================================================================
" syntastic 插件
"====================================================================
let g:syntastic_javascript_checkers = ['eslint']

"====================================================================
" NERDTree 插件
"====================================================================

" 打开和关闭NERDTree快捷键
map <F9> :NERDTreeToggle<CR>
" 显示行号
let NERDTreeShowLineNumbers=1
" 打开文件时是否显示目录
let NERDTreeAutoCenter=0
" 是否显示隐藏文件
let NERDTreeShowHidden=0
" 设置宽度
let NERDTreeWinSize=31
" 忽略一下文件的显示
let NERDTreeIgnore=['\.pyc','\~$','\.swp','__pycache__']
" 在终端启动vim时，共享NERDTree
let g:nerdtree_tabs_open_on_console_startup=0
" 显示书签列表
let NERDTreeShowBookmarks=1

"====================================================================
"  nerdtree-git-plugin 插件
"====================================================================
au FileType python let NERDSpaceDelims=1           " python文件类型时，让注释符与语句之间留一个空格
let NERDCompactSexyComs=1       " 多行注释时样子更好看
let g:NERDDefaultAlign = 'left'  "将行注释符左对齐

let g:NERDTreeGitStatusIndicatorMapCustom = {
    \ "Modified"  : "✹",
    \ "Staged"    : "✚",
    \ "Untracked" : "✭",
    \ "Renamed"   : "➜",
    \ "Unmerged"  : "═",
    \ "Deleted"   : "✖",
    \ "Dirty"     : "✗",
    \ "Clean"     : "✔︎",
    \ 'Ignored'   : '☒',
    \ "Unknown"   : "?"
    \ }

" let g:NERDTreeShowIgnoredStatus = 1
let g:NERDTreeGitStatusShowIgnored = 1

"====================================================================
"  majutsushi/tagbar 插件
"====================================================================

" majutsushi/tagbar 插件打开关闭快捷键
nmap <F10> :TagbarToggle<CR>
autocmd BufReadPost *.cpp,*.c,*.h,*.hpp,*.cc,*.cxx,*.py call tagbar#autoopen()


"====================================================================
"  Valloric/YouCompleteMe 插件
"====================================================================

" make YCM compatible with UltiSnips (using supertab)
" let g:ycm_global_ycm_extra_conf='~/.vim/.ycm_extra_conf.py'
let g:ycm_key_list_select_completion = ['<C-n>', '<space>']
let g:ycm_key_list_previous_completion = ['<C-p>', '<Up>']
let g:SuperTabDefaultCompletionType = '<C-n>'
"按gd 会跳转到定义
nnoremap gd :YcmCompleter GoToDefinitionElseDeclaration<CR>   
" 开启 YCM 基于标签引擎
let g:ycm_collect_identifiers_from_tags_files=1
" 从第2个键入字符就开始罗列匹配项
let g:ycm_min_num_of_chars_for_completion=2
" 禁止缓存匹配项,每次都重新生成匹配项
let g:ycm_cache_omnifunc=0
" 语法关键字补全
let g:ycm_seed_identifiers_with_syntax=1

let g:ycm_semantic_triggers = {
   \   'css': [ 're!^\s{2,4}', 're!:\s+' ],
   \ }

let g:ycm_show_diagnostics_ui = 1 " 开启实时错误或者warning的检测
let g:ycm_add_preview_to_completeopt = 0 " 关闭补全预览
" 补全内容不以分割子窗口形式出现，只显示补全列表
"set completeopt-=preview
let g:ycm_complete_in_comments=1 " 补全功能在注释中同样有效
let g:ycm_error_symbol = '✗' " 错误标记
"let g:ycm_warning_symbol = 'w' " warning标记

" better key bindings for ultisnipsexpandtrigger
let g:ultisnipsexpandtrigger = "<tab>"
let g:ultisnipslistsnippets = "<c-tab>"
let g:ultisnipsjumpforwardtrigger = "<tab>"
let g:ultisnipsjumpbackwardtrigger = "<s-tab>"
let g:snips_author = 'bobo'
let g:snips_email = 'gg-tc@163.com'
let g:snips_github = 'gitee.com/bongem'
" 自定义补全 .vim/mysnippets/
" let g:ultisnipssnippetdirectories=["ultisnips","mysnippets"]

"====================================================================
" rainbow_parentheses
"====================================================================
"RGB彩色括号
let g:rbpt_colorpairs = [
        \ ['brown',       'RoyalBlue3'],
        \ ['Darkblue',    'SeaGreen3'],
        \ ['darkgray',    'DarkOrchid3'],
        \ ['darkgreen',   'firebrick3'],
        \ ['darkcyan',    'RoyalBlue3'],
        \ ['darkred',     'SeaGreen3'],
        \ ['darkmagenta', 'DarkOrchid3'],
        \ ['brown',       'firebrick3'],
        \ ['gray',        'RoyalBlue3'],
        \ ['black',       'SeaGreen3'],
        \ ['darkmagenta', 'DarkOrchid3'],
        \ ['Darkblue',    'firebrick3'],
        \ ['darkgreen',   'RoyalBlue3'],
        \ ['darkcyan',    'SeaGreen3'],
        \ ['darkred',     'DarkOrchid3'],
        \ ['red',         'firebrick3'],
        \ ]
let g:rbpt_max = 16
let g:rbpt_loadcmd_toggle = 0
au VimEnter * RainbowParenthesesToggle
au Syntax * RainbowParenthesesLoadRound
au Syntax * RainbowParenthesesLoadSquare
au Syntax * RainbowParenthesesLoadBraces

"=====================================================================
" Chiel92/vim-autoformat配置
"=====================================================================
"nnoremap <F6> :Autoformat<CR>
"let g:autoformat_autoindent = 0
"let g:autoformat_retab = 0
"let g:autoformat_remove_trailing_spaces = 0
"let g:autoformat_verbosemode=1


"===================================================================
" w0rp/ale配置
"===================================================================
"let g:ale_fix_on_save = 1
let g:ale_completion_enabled = 1
let g:ale_sign_column_always = 1
let g:airline#extensions#ale#enabled = 1
let g:ale_set_highlights = 0
"自定义error和warning图标
let g:ale_sign_error = '✗'
let g:ale_sign_warning = '⚡'
"在vim自带的状态栏中整合ale
let g:ale_statusline_format = ['✗ %d', '⚡ %d', '✔ OK']
"显示Linter名称,出错或警告等相关信息
let g:ale_echo_msg_error_str = 'E'
let g:ale_echo_msg_warning_str = 'W'
let g:ale_echo_msg_format = '[%linter%] %s [%severity%]'
"打开文件时不进行检查
let g:ale_lint_on_enter = 0

"普通模式下，sp前往上一个错误或警告，sn前往下一个错误或警告
nmap sp <Plug>(ale_previous_wrap)
nmap sn <Plug>(ale_next_wrap)
"<Leader>s触发/关闭语法检查
nmap <Leader>s :ALEToggle<CR>
"<Leader>d查看错误或警告的详细信息
nmap <Leader>d :ALEDetail<CR>
"使用clang对c和c++进行语法检查，对python使用pylint进行语法检查
let g:ale_linters = {
\   'c++': ['clang'],
\   'c': ['clang'],
\   'python': ['pylint'],
\}
let g:ale_fixers = {
\    'python': ['yapf', 'isort'],
\}
noremap <F2> :ALEFix<CR>

" markdwon 的快捷键
map <silent> <F7> <Plug>StopMarkdownPreview
map <silent> <F8> <Plug>MarkdownPreview

" tab 标签页切换快捷键
:nn <Leader>1 1gt
:nn <Leader>2 2gt
:nn <Leader>3 3gt
:nn <Leader>4 4gt
:nn <Leader>5 5gt
:nn <Leader>6 6gt
:nn <Leader>7 7gt
:nn <Leader>8 8gt
:nn <Leader>x :tabc<CR>
:nn <Leader>0 :tablast<CR>


" F5 to run sh/python3
map <F5> :call CompileRunGcc()<CR>
imap <F5> <ESC>:call CompileCode()<CR>
func! CompileRunGcc()
    exec "w"
    if &filetype == 'sh'
        :!time bash %
    elseif &filetype == 'python'
        exec "!time python3 %"
    elseif &filetype == 'go'
        exec "!time go run %"
    endif
endfunc

" 自定义html标签闭合
inoremap ></ ><ESC>%lyEh%a</<C-R>=AutoTag()<CR><ESC>F<i<CR><ESC>kA<CR>
func! AutoTag()
  return substitute(@0, '>', '', 'g').'>'
endfunc

if (empty($TMUX))
  if (has("nvim"))
    "For Neovim 0.1.3 and 0.1.4 < https://github.com/neovim/neovim/pull/2198 >
    let $NVIM_TUI_ENABLE_TRUE_COLOR=1
  endif
  "For Neovim > 0.1.5 and Vim > patch 7.4.1799 < https://github.com/vim/vim/commit/61be73bb0f965a895bfb064ea3e55476ac175162 >
  "Based on Vim patch 7.4.1770 (`guicolors` option) < https://github.com/vim/vim/commit/8a633e3427b47286869aa4b96f2bfc1fe65b25cd >
  " < https://github.com/neovim/neovim/wiki/Following-HEAD#20160511 >
  if (has("termguicolors"))
    set termguicolors
  endif
endif
set background=dark " for the dark version
" set background=light " for the light version
colorscheme one
" 设置背景透明
hi Normal ctermbg=NONE guibg=NONE

""===================================================================
" GVim 的配置
"===================================================================
" 如果不使用 GVim ，可以不用配置下面的配置
if has('gui_running')
    colorscheme one
    " 设置启动时窗口的大小
    set lines=999 columns=999 linespace=4

    " 设置字体及大小
    set guifont=Roboto\ Mono\ 13

    set guioptions-=m " 隐藏菜单栏
    set guioptions-=T " 隐藏工具栏
    set guioptions-=L " 隐藏左侧滚动条
    set guioptions-=r " 隐藏右侧滚动条
    set guioptions-=b " 隐藏底部滚动条
    " 在 gvim 下不会和 terminal 的 alt+数字的快捷键冲突，
    " 所以将 tab 切换配置一份 alt+数字的快捷键
    :nn <M-1> 1gt
    :nn <M-2> 2gt
    :nn <M-3> 3gt
    :nn <M-4> 4gt
    :nn <M-5> 5gt
    :nn <M-6> 6gt
    :nn <M-7> 7gt
    :nn <M-8> 8gt
    :nn <M-9> 9gt
    :nn <M-0> :tablast<CR>
endif

" 保持 Quickfix 在下方
" augroup DragQuickfixWindowDown
"     autocmd!
"     autocmd FileType qf wincmd J
" augroup end

